如何从Switch调用函数

时间:2018-04-09 19:56:37

标签: dart flutter

使用Flutter中创建的默认Android Studio应用,我尝试测试Switch,因此我添加了以下代码:

new Switch(value: true, onChanged: (bool newValue) {
  setState(() {
    _incrementCounter();  // executed only if the value is true
  });
},),

incrementCounter功能是:

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

我的问题是incrementCounter函数在Switch值切换回false后被调用并执行,而我期望的是incrementCounter每次切换开关时都应该调用函数,即无论新值是真还是假!

3 个答案:

答案 0 :(得分:2)

as @aziza说问题是:

  

您没有切换值。

所以这应该有用

class MyApp extends StatefulWidget {
  @override
  MyAppState createState() {
    return new MyAppState();
  }
}

class MyAppState extends State<MyApp> {
  var _value=false;
  var inc=0;
  onchange(bool value){
    setState((){
     inc++;
     _value=value;
    });
  }
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(),
      body : new Column(children: <Widget>[
        new Switch(value: _value, onChanged: (bool value)=>onchange(value)),
        new Center(child: new Text("value ${inc}"),)
      ],)
    );
  }
}

enter image description here

答案 1 :(得分:1)

您没有切换值。

错误基本上在此行的代码中:

value: true

您可以使用类级别布尔来处理此问题。

示例:

//State level class

bool switchValue = false;
  _dummyMethod(){
    print (this.switchValue);
  }
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(),
      body: new Center(
        child: new Switch(
          onChanged: (newValue){
            setState((){
              this.switchValue = newValue;
            });
            _dummyMethod();
          },
         value: switchValue,)
      ),
    );
  }

答案 2 :(得分:0)

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.deepOrange,
      ),
      home: new MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  var _value=false;
  double _bodyHeight=0.0;

  void onchange(bool value) {
    setState(() {
      _value = value;
      this._bodyHeight = (value == true) ? 400.0 : 0.0;
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      backgroundColor: Colors.grey[500],
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new SingleChildScrollView(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Card(
              child: new Container(
                height: 50.0,
                child: new Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: <Widget>[
                    new Text("Select me pls"),
                    new Switch(value: _value, onChanged: (bool value) => onchange(value)),
                  ],
                ),
              ),
            ),
            new Card(
              child: new AnimatedContainer(
                child: new ListView(
                  children: <Widget>[
                      new ListTile(
                      leading: const Icon(Icons.person),
                      title: new TextField(
                        decoration: new InputDecoration(
                          hintText: "Name",
                        ),
                      ),
                    ),
                    new ListTile(
                      leading: const Icon(Icons.phone),
                      title: new TextField(
                        decoration: new InputDecoration(
                          hintText: "Phone",
                        ),
                      ),
                    ),
                    new ListTile(
                      leading: const Icon(Icons.email),
                      title: new TextField(
                        decoration: new InputDecoration(
                          hintText: "Email",
                        ),
                      ),
                    ),
                    const Divider(
                      height: 1.0,
                    ),
                    new ListTile(
                      leading: const Icon(Icons.label),
                      title: const Text('Nick'),
                      subtitle: const Text('None'),
                    ),
                    new ListTile(
                      leading: const Icon(Icons.today),
                      title: const Text('Birthday'),
                      subtitle: const Text('February 20, 1980'),
                    ),
                      new ListTile(
                        leading: const Icon(Icons.group),
                        title: const Text('Contact group'),
                        subtitle: const Text('Not specified'),
                      ),
                      new ListTile(
                        leading: const Icon(Icons.person),
                        title: new TextField(
                          decoration: new InputDecoration(
                            hintText: "Name",
                          ),
                        ),
                      ),
                      new ListTile(
                        leading: const Icon(Icons.phone),
                        title: new TextField(
                          decoration: new InputDecoration(
                            hintText: "Phone",
                          ),
                        ),
                      ),
                      new ListTile(
                        leading: const Icon(Icons.email),
                        title: new TextField(
                          decoration: new InputDecoration(
                            hintText: "Email",
                          ),
                        ),
                      ),
                      const Divider(
                        height: 1.0,
                      ),
                      new ListTile(
                        leading: const Icon(Icons.label),
                        title: const Text('Nick'),
                        subtitle: const Text('None'),
                      ),
                      new ListTile(
                        leading: const Icon(Icons.today),
                        title: const Text('Birthday'),
                        subtitle: const Text('February 20, 1980'),
                      ),
                      new ListTile(
                        leading: const Icon(Icons.group),
                        title: const Text('Contact group'),
                        subtitle: const Text('Not specified'),
                      )
                  ],
                ),
                curve: Curves.easeInOut,
                duration: const Duration(milliseconds: 500),
                height: _bodyHeight,
                // color: Colors.red,
              ),
            ),
          ],
        ),
      ),
    );
  }
}