Flutter bottomSheet для изменения основного состояния приложения - PullRequest
1 голос
/ 18 февраля 2020

Мой main.dart стал довольно длинным, поэтому я делю его на различные другие .dart файлы для удобства обслуживания.

Мое главное приложение использует объект Google Map, и я размещаю на нем различные красные маркеры местоположения. Теперь у меня есть различные FloatingActionButton() внизу - каждый открывает нижний лист, используя showBottomSheet() или showModalBottomSheet().

Единственный способ, которым я могу сейчас думать, разделить основное приложение на различные файлы ( держать в порядке) значит хранить содержимое этих различных нижних листов в разных .dart файлах, которые затем вызываются из main.dart - возможно, неправильный путь.

enter image description here

Main.dart

...
import 'package:flutter_app/db_manager.dart' as db_manager;

import 'package:flutter_app/section_about.dart';
import 'package:flutter_app/section_settings.dart';

void main() => runApp(MyApp());

SectionAbout sectionAbout = SectionAbout();
SectionSettings sectionSettings = SectionSettings();

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  GoogleMapController mapController;

  static const LatLng _center = const LatLng(xxxxxxx, xxxxxxx); 

  void _onMapCreated(GoogleMapController controller) {
    mapController = controller;
  }

  void _onCameraMove(CameraPosition position) {
    _lastMapPosition = position.target;
  }

  final Set<Marker> _markers = {};
  MapType _currentMapType = MapType.normal;
  LatLng _lastMapPosition = _center;


  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('My Map'),
          backgroundColor: Colors.green[700],
        ),

        //Put in a stack widget so can layer other widgets on top of map widget
        body: Stack(
          children: <Widget>[
            GoogleMap(
              mapType: _currentMapType,
              markers: _markers,
              onMapCreated: _onMapCreated,
              onCameraMove: _onCameraMove,
              initialCameraPosition: CameraPosition(
                target: _center,
                zoom: 11.0,
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Align(
                  alignment: Alignment.bottomCenter,
                  child: Row(mainAxisSize: MainAxisSize.min, children: <Widget>[

                    SizedBox(width: 16.0),

                    Builder(
                      builder: (context) => FloatingActionButton(
                          child: Icon(Icons.settings, size: 36.0),
                          backgroundColor: Colors.green,
                          onPressed: () {

                            sectionSettings.onSheetShowContents(context);       <------

                          }),
                    ),

                    SizedBox(width: 16.0),
                    FloatingActionButton(
                      onPressed: _onDownloadTestPressed,
                      materialTapTargetSize: MaterialTapTargetSize.padded,
                      backgroundColor: Colors.green,
                      child: const Icon(Icons.autorenew, size: 36.0),
                    ),

                    SizedBox(width: 16.0),

                    Builder(
                      builder: (context) => FloatingActionButton(
                          child: Icon(Icons.help, size: 36.0),
                          backgroundColor: Colors.green,
                          onPressed: () {

                            sectionAbout.onSheetShowContents(context);       <------

                          }),
                    ),

                    SizedBox(width: 16.0),

                    FloatingActionButton(
                      onPressed: _onDBActions,
                      materialTapTargetSize: MaterialTapTargetSize.padded,
                      backgroundColor: Colors.green,
                      child: const Icon(Icons.change_history, size: 36.0),
                    ),
                  ])),
            ),
          ],
        ),
      ),
    );
  }
}




Settings.dart

import 'package:flutter/material.dart';
import 'package:flutter_app/db_manager.dart' as db_manager;

class SectionSettings {

  int mapTypeView = 0;

  void onSheetShowContents(Context context) {

    showModalBottomSheet(
      //showBottomSheet(
        context: context,
        builder: (context) {
          return ListView(
            padding: EdgeInsets.all(15.0),
            children: <Widget>[
              ListTile(
                title: Text("Map Settings"),
                selected: true,
              ),

              Divider(),

              Row(
                mainAxisAlignment:
                MainAxisAlignment.spaceEvenly,
                children: [
                  Column(
                    children: <Widget>[
                      Text("Map View"),
                    ],
                  ),
                  Column(
                    children: <Widget>[
                      Row(
                        children: <Widget>[
                          ChoiceChip(
                            label: Text("Normal Map"),
                            selected: mapTypeView == 0,
                            onSelected: (value) {
                              setState(() {
                                mapTypeView = 0;
                                _currentMapType =
                                    MapType.normal;
                              });
                            },
                          ),
                          SizedBox(width: 8),
                          ChoiceChip(
                            label: Text("Satelite Map"),
                            selected: mapTypeView == 1,
                            onSelected: (value) {
                              setState(() {
                                mapTypeView = 1;
                                _currentMapType =
                                    MapType.satellite;
                              });
                            },
                          ),
                        ],
                      ),
                    ],
                  )
                ],
              ),


            ],
            // ),
          );
        });
  }
}

Обратите внимание, как я использую <OtherDartFileName>.onSheetShowContents(); и этот код перемещен в <OtherDartFileName> вместо того, чтобы иметь большой раздел здесь в главном файле дротика.

Это привело к проблеме, из-за которой я не могу изменить State карты Google из этого нижнего листа поскольку он не имеет ссылки (и я не могу передать его) основного состояния приложения.

  • Я хочу иметь нижний лист, содержащий кнопку, которая переключает обычный вид и спутниковый вид на главной карте (и, в конечном итоге, другие варианты)

  • Есть Я совершенно неправильно структурировал этот проект, или я могу просто как-то ссылаться на состояние карты?

У меня также есть отдельные файлы .dart для одного экземпляра SQFlite и управления всеми операциями БД. Кодирование для android и, в конечном итоге, приведет к iOS.

Большое спасибо

...