简体   繁体   中英

Flutter: setState() called in constructor

I am novice in Flutter, and ran upon a problem trying to show a map and implement some tilelayers.

The app has a Drawer implemtation where I want to enable/disable and clear the tile cache.

I have fetched some examples where this was working well, so I know that the tiling works great, but here i ran upon a problem where I want to call member functions of the MyWorldMap stateful widget from the drawer widget, and to my spare knowledge I now are plagued by the setState() called in constructor error message.

Do you have any suggestions to help, or guide me on the correct path ?

Note !! Remember to add your own MAP API KEY according to: https://codelabs.developers.google.com/codelabs/google-maps-in-flutter?hl=en&continue=https%3A%2F%2Fcodelabs.developers.google.com%2F#3

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:http/http.dart' as http;


void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget{
  const MyApp({Key? key}) : super(key: key);


  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title:"My App test",
      theme: ThemeData(primarySwatch: Colors.blue),
      home: HomePage(title: "My World Map")
    );
  }
}

class HomePage extends StatefulWidget{

  final String title;

  HomePage({Key? key, required this.title}):super(key: key);

  @override
  _HomePageState createState() => _HomePageState();

}

class _HomePageState extends State<HomePage>{
  @override
  void initState(){
    super.initState();
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      drawer: MainDrawer(),
      body: MyWorldMap(),
    );

  }


}

class MainDrawer extends StatefulWidget{

  @override
  State<StatefulWidget> createState() => MainDrawerState();
}

class MainDrawerState extends State<MainDrawer>{

  @override
  Widget build(BuildContext context) {

    return Drawer(
      child: ListView(
        padding: EdgeInsets.zero,
        children: <Widget>[
          const DrawerHeader(
            decoration: BoxDecoration(color: Colors.blue),
            child: Text("My World Map"),
          ),
          ListTile(
            title: const Text ("Add tile overlay"),
            onTap: () => addTileOverlay(),
          ),
          ListTile(
              title: const Text ("Clear tile overlay cache"),
              onTap: () => clearTileCache(),
          ),
          ListTile(
              title: const Text ("Remove tile overlay"),
              onTap: () => removeTileOverlay(),
          ),

        ],
      ),
    );

  }

  void addTileOverlay(){
    print("Attempting to add tile overlay");
    MyWorldMap().addTileOverlay();
  }

  void clearTileCache(){
    print("Attempting clear tile cache");
    MyWorldMap().clearTileCache();
  }

  void removeTileOverlay(){
    print("Attempting removing tile overlay");
    MyWorldMap().removeTileOverlay();
  }

}

class MyWorldMap extends StatefulWidget{
  const MyWorldMap({Key? key}) : super(key: key);

  addTileOverlay() => createState()._addTileOverlay();
  removeTileOverlay() => createState()._removeTileOverlay();
  clearTileCache() => createState()._clearTileCache();

  @override
  _MyWorldMapState createState() => _MyWorldMapState();
}

class _MyWorldMapState extends State<MyWorldMap>
{
  TileOverlay? _tileOverlay;
  late GoogleMapController _mapController;
  final LatLng _initialCameraPosition = const LatLng(61.9026,6.7003); //Change with your location

  //You need to change maps API key in AndroidManifest.xml

  @override
  void initState(){
    super.initState();
  }

  Future<void> _onMapCreated(GoogleMapController controller) async {
    _mapController = controller;
    setState(() {
      //Do stuff ?
    });
  }

  @override
  Widget build(BuildContext context) {
    Set<TileOverlay> overlays = <TileOverlay>{
      if(_tileOverlay != null) _tileOverlay!,
    };

    return GoogleMap(
      onMapCreated: _onMapCreated,
      initialCameraPosition: CameraPosition(
        target: _initialCameraPosition,
        zoom:15,
      ),
      myLocationEnabled: false,
      tileOverlays: overlays,
    );

  }

  void _addTileOverlay()
  {
    final TileOverlay tileOverlay = TileOverlay(
      tileOverlayId: TileOverlayId("My World Map Overlay"),
      tileProvider: MyWorldMapTileProvider(),
    );
    setState((){   //The code fails here when pushing the 'Add tile overlay button' !!
      _tileOverlay = tileOverlay;
    });
  }

  void _clearTileCache()
  {
    if(_tileOverlay != null){
      _mapController.clearTileCache(_tileOverlay!.tileOverlayId);
    }
  }

  void _removeTileOverlay()
  {
    setState(() {
      _tileOverlay = null;
    });
  }

}

class MyWorldMapTileProvider implements TileProvider {

  @override
  Future<Tile> getTile(int x, int y, int? zoom) async {

    String path = 'https://maptiles1.finncdn.no/tileService/1.0.1/norortho/$zoom/$x/$y.png';

    http.Response response = await http.get(
      Uri.parse(path)
    );

    return Tile(x,y,response.bodyBytes);
  }

}



Seems like you are using setState before build method has finished building the widgets. I would suggest using setState after build has finished, this way :

       WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
          setState(() {
            // do stuff;
          });
        });

Not that I am a real professional with flutter, but I think the problem might reside in here:

addTileOverlay() => createState()._addTileOverlay();    
removeTileOverlay() => createState()._removeTileOverlay();
clearTileCache() => createState()._clearTileCache();

You're creating a new state each time you invoke one of those methods in MyWorldMap widget, and I don't think that's the correct behaviour.

If you want to edit a Widget state from another Widget, you should try using keys: I think any stateful Widget can take a key argument in the constructor, that can be used in turn to change its state from other widgets. I'll try writing a simple example.

class Parent extends StatelessWidget {
final keyA = GlobalKey();
final keyB = GlobalKey();

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Column(children: [
      ChildA(keyA),
      ChildB(keyB, keyA),
    ]),
  );
  }
}

class ChildA extends StatefulWidget {
 const ChildA(GlobalKey key) : super(key: key);

 @override
 State<StatefulWidget> createState() => ChildAState();
}

class ChildAState extends State<ChildA> {
 int counter = 0;
 @override
 Widget build(BuildContext context) {
  return Text("Child A count: $counter");
 }

 void increaseCounter(){
   setState(() {
     counter++;
   });
 }
}

class ChildB extends StatefulWidget {
 final GlobalKey childAKey;
 const ChildB(GlobalKey key, this.childAKey) : super(key: key);

 @override
 State<StatefulWidget> createState() => ChildBState();
}

class ChildBState extends State<ChildB> {
  @override
  Widget build(BuildContext context) {
  return TextButton(
    child: const Text("Press here"),
    onPressed: () {
      (widget.childAKey.currentState as ChildAState).increaseCounter();
    },
  );
 }
}

After @il_boga lead me to the answer (all credits to him), I'll post the working code here:

I moved the TileOverlay creation to initState of _MyWorldMapState class, and added a buffered 'layer' too so I could switch on/off the layer by setting _mapTileOverlay to null when removing and back to _bufferedMapTileOverlay when adding the overlay.

Further I have created two GlobalKeys (actually not knowing why i need drawerKey actually, since I never activily reference it anywhere..., mapKey is obvious)


import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget{
  const MyApp({Key? key}) : super(key: key);
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title:"My App test",
      theme: ThemeData(primarySwatch: Colors.blue),
      home: HomePage(title: "My World Map")
    );
  }
}

class HomePage extends StatefulWidget{
  final String title;

  const HomePage({Key? key, required this.title}):super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>{

  final drawerKey = GlobalKey();
  final mapKey = GlobalKey();

  @override
  void initState(){
    print("_HomePageState(): initState");
    super.initState();
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      drawer: MainDrawer(drawerKey: drawerKey, mapKey: mapKey,),
      body: MyWorldMap(mapKey: mapKey,),
    );
  }
}

class MainDrawer extends StatefulWidget{

  final GlobalKey mapKey;

  const MainDrawer({required GlobalKey drawerKey, required this.mapKey}) : super(key: drawerKey);

  @override
  State<StatefulWidget> createState() => MainDrawerState();
}

class MainDrawerState extends State<MainDrawer>{



  @override
  Widget build(BuildContext context) {

    return Drawer(
      child: ListView(
        padding: EdgeInsets.zero,
        children: <Widget>[
          const DrawerHeader(
            decoration: BoxDecoration(color: Colors.blue),
            child: Text("My World Map"),
          ),
          ListTile(
            title: const Text ("Add tile overlay"),
            onTap: () => addTileOverlay(),
          ),
          ListTile(
              title: const Text ("Clear tile overlay cache"),
              onTap: () => clearTileCache(),
          ),
          ListTile(
              title: const Text ("Remove tile overlay"),
              onTap: () => removeTileOverlay(),
          ),

        ],
      ),
    );

  }

  void addTileOverlay(){
    print("Attempting to add tile overlay");
    //MyWorldMap().addTileOverlay();
    (widget.mapKey.currentState as _MyWorldMapState)._addTileOverlay();
  }

  void clearTileCache(){
    print("Attempting clear tile cache");
    //MyWorldMap().clearTileCache();
    (widget.mapKey.currentState as _MyWorldMapState)._clearTileCache();
  }

  void removeTileOverlay(){
    print("Attempting removing tile overlay");
    //MyWorldMap().removeTileOverlay();
    (widget.mapKey.currentState as _MyWorldMapState)._removeTileOverlay();
  }

}

class MyWorldMap extends StatefulWidget{
  const MyWorldMap({required GlobalKey mapKey}) : super(key: mapKey);

  //addTileOverlay() => createState()._addTileOverlay();
  //removeTileOverlay() => createState()._removeTileOverlay();
  //clearTileCache() => createState()._clearTileCache();

  @override
  _MyWorldMapState createState() => _MyWorldMapState();
}

class _MyWorldMapState extends State<MyWorldMap>
{
  TileOverlay? _bufferedMapTileOverlay; //intermediate, which actually holds the overlay
  TileOverlay? _mapTileOverlay; //value which connects to the map
  late GoogleMapController _mapController;
  final LatLng _initialCameraPosition = const LatLng(61.9026,6.7003); //Change with your location

  //You need to change maps API key in AndroidManifest.xml

  @override
  void initState(){
    print("_MyWordMapState(): initState");
    super.initState();

    final TileOverlay newMapTileOverlay = TileOverlay(  //Inits the tileOverlay
      tileOverlayId: const TileOverlayId("My World Map Overlay"),
      tileProvider: MyWorldMapTileProvider(),
    );

    _bufferedMapTileOverlay = newMapTileOverlay;
  }

  Future<void> _onMapCreated(GoogleMapController controller) async {
    _mapController = controller;
    setState(() {
      //Do stuff ?
    });
  }

  @override
  Widget build(BuildContext context) {
    Set<TileOverlay> overlays = <TileOverlay>{  //connect a set of overlays (here just one)
      if(_mapTileOverlay != null) _mapTileOverlay!,
    };

    return GoogleMap(
      onMapCreated: _onMapCreated,
      initialCameraPosition: CameraPosition(
        target: _initialCameraPosition,
        zoom:15,
      ),
      myLocationEnabled: false,
      tileOverlays: overlays, //connect to the set of overlays (I have only one (see above))
    );

  }

  void _addTileOverlay()
  {
    setState((){
      _mapTileOverlay = _bufferedMapTileOverlay;
    });
  }

  void _clearTileCache()
  {
    if(_mapTileOverlay != null){
      print("Clearing tile cache");
      _mapController.clearTileCache(_mapTileOverlay!.tileOverlayId);
    }
  }

  void _removeTileOverlay()
  {
    setState(() {
      _mapTileOverlay = null;
    });
  }

}

class MyWorldMapTileProvider implements TileProvider {

  @override
  Future<Tile> getTile(int x, int y, int? zoom) async {

    String path = 'https://maptiles1.finncdn.no/tileService/1.0.1/norortho/$zoom/$x/$y.png';

    http.Response response = await http.get(
      Uri.parse(path)
    );

    return Tile(x,y,response.bodyBytes);
  }

}


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM