简体   繁体   中英

How to pass setstate as a parameter to a class method

in flutter I use a class to load values for switch widgets from a database and then update that database when the switch is toggled. Somehow I need to have that class call setstate on the calling function of the instance but it doesn't seem to work. See the code below for an example.

  • The first switch is how I'd write it without the database class. That is working fine, when tapping the switch it both moves and the print shows that the value changed.

  • In the second switch widget however, I used the database class to build it but it doesn't seem to call the callback function correctly. The print always prints false.

I thought I tried all combinations of => and (){} but something is still amiss. I'm pretty sure the problem is how the callback is handled in the line: callBackFunctionForSetState(); maybe that should be called with callBackFunctionForSetState((){}); but that also doesn't work.

import 'package:flutter/material.dart';

void main()  {
  runApp(App());
}

bool myBool = true;

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Title',
      home: ScreenUpgrades(),
    );
  }
}

class ScreenUpgrades extends StatefulWidget {
  @override
  _ScreenUpgradesState createState() => _ScreenUpgradesState();
}

class _ScreenUpgradesState extends State<ScreenUpgrades> {
  @override
  Widget build(BuildContext ctxt) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text("Upgrades"),
        ),
        body: FutureBuilder(
            future: buildSwitchList(),
            builder: (BuildContext ctxt, AsyncSnapshot snapshot) {
              if (snapshot.hasData) {
                return ListView(children: snapshot.data);
              } else {
                return Center(child: CircularProgressIndicator());
              }
            }));
  }
  Future<List> buildSwitchList() async {
    List<Widget> widgetList = [];
    //This one below for a working example only
    widgetList.add(Switch(value: myBool,onChanged: (bb)=>nonDBSetState()));

    //Normally I'll create a bunch of widgets by loading their data from the DB as below
    widgetList.add(DataBaseSwitchBuilder(1,()=>setState((){})).listViewWidget);
    return widgetList;
  }
  nonDBSetState()
  {
    myBool = !myBool;
    print('New value of first switch: ' + myBool.toString());
    setState((){});
  }
}

class DataBaseSwitchBuilder {
  Widget listViewWidget;
  int dbID;
  bool onOff;
  Function callBackFunctionForSetState;
  DataBaseSwitchBuilder (int paramID, Function callBack)
  {
    dbID=paramID; //used to query the parameter from the DB
    onOff = true;
    callBackFunctionForSetState=callBack;
    listViewWidget=(Switch(value: onOff,onChanged: (bb)=> updateDBAndState()));
  }
  updateDBAndState()
  {
    //update the switch
    onOff = !onOff;
    print('DB Swtich value now: ' + onOff.toString());
    //first we save the record in the DB
        //todo: code for updating DB
    //Then call the passed function which should be a setstate from the calling function
    //Below doesn't seem to work.
    callBackFunctionForSetState();
  }
}

I'm just expecting that the updateDBAndState will allow me to save the new value of the switch to the database and then call the setstate callback.

Just to respond to "How to pass setstate as a parameter to a class method"

widget controler

class Controller {
  Controller._privateConstructor();

  factory Controller() => _singleton;

  static final Controller _singleton =
      Controller._privateConstructor();

  late Function setStateHandler;

  void initSetState(Function setState) => setStateHandler = setState;

  void triggerSetState() => setStateHandler();
}

widget

@override
  void initState() {
    super.initState();
    controller.initSetState(() => setState(() {
      widgetVariable = true;
    }));
}

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