简体   繁体   English

使用 Flutter 提供程序 package 时出现问题

[英]Problems while using Flutter Provider package

I am creating a very simple app to practice flutter provider package.我正在创建一个非常简单的应用程序来练习 flutter 提供者 package。 The app has a bulb which on click, should change it's background and the screen's background, using provider.该应用程序有一个灯泡,单击时应使用提供程序更改其背景和屏幕背景。 But this doesnt seem to work.但这似乎不起作用。 TBH this is a lot confusing TBH 这很令人困惑

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

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

class Data extends ChangeNotifier{
  bool isOn = false;
  void toggle(){
    this.isOn = !this.isOn;
    notifyListeners();
    print("new value is $isOn");
  }
}

class MainApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<Data>(
      create: (context) => Data(),
      child: MaterialApp(
        home: Home(),
      ),
    );
  }
}

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      backgroundColor: Provider.of<Data>(context).isOn ? Colors.yellow[100] : Colors.black,
      body: Center(
        child: Column(
          children: <Widget>[
            Stick(),
            Bulb(),
          ],
        ),
      ),
    );
  }
}

class Stick extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 150,
      width: 40,
      color: Colors.brown,
    );
  }
}

class Bulb extends StatefulWidget {
  @override
  _BulbState createState() => _BulbState();
}

class _BulbState extends State<Bulb> {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 200,
      width: 250,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(100),
              topRight: Radius.circular(100),
              bottomLeft: Radius.circular(30),
              bottomRight: Radius.circular(30)),
          color: Provider.of<Data>(context).isOn ? Colors.yellow : Colors.white,
      ),
      child: GestureDetector(
        onTap: (){
          Provider.of<Data>(context).toggle();
          setState(() {
          });
        },
      ),
    );
  }
}

The tree structure has a main app which houses a Home app, which houses 2 other widgets, a stick and a bulb inside a container.树结构有一个主应用程序,其中包含一个 Home 应用程序,其中包含 2 个其他小部件,一个容器内的棒和一个灯泡。 I am trying to update the background of bulb and the Home widget when the bulb is clicked.单击灯泡时,我正在尝试更新灯泡的背景和 Home 小部件。 Bulb has a gesture detector Any kind of hint or help appreciated灯泡有一个手势检测器任何类型的提示或帮助表示赞赏

Try to add listen: false to the provider call:尝试在提供者调用中添加listen: false

Provider.of<Data>(context, listen: false).toggle();

The problem is because Provider constructor has a named parameter listen which is equal to true by default.问题是因为Provider构造函数有一个命名参数listen ,默认情况下它等于true And this behavour force rebuilding while you use Provider.of() method.当您使用Provider.of()方法时,这种行为会强制重建。 It is imposible to call build while current buiding is still active.在当前的构建仍处于活动状态时调用build是不可能的。 That is why you suggested to set listen to false because it disables default behavour.这就是为什么您建议将listen设置为false的原因,因为它会禁用默认行为。

It is better to implement like this:最好像这样实现:

...

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return Consumer<Data>(
      builder: (_, data, __) {
        return Scaffold(
          appBar: AppBar(),
          backgroundColor: data.isOn ? Colors.yellow[100] : Colors.black,
          body: Center(
            child: Column(
              children: <Widget>[
                Stick(),
                Bulb(),
              ],
            ),
          ),
        );
      }
    );
  }
}
...

class _BulbState extends State<Bulb> {
  @override
  Widget build(BuildContext context) {
    return Consumer<Data>(
      builder: (_, data, __) {
        return Container(
          height: 200,
          width: 250,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(100),
              topRight: Radius.circular(100),
              bottomLeft: Radius.circular(30),
              bottomRight: Radius.circular(30)
            ),
            color: data.isOn ? Colors.yellow : Colors.white,
          ),
          child: GestureDetector(
            onTap: () {
              data.toggle();
              setState(() {});
            },
          ),
        );
      },
    );
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 flutter 中使用 path_provider package 时出错 - Error using path_provider package in flutter 与 Flutter 提供程序包相关的错误 - Error related to Flutter provider package Flutter 应用程序在使用 flutter_pdfview package 时崩溃 - Flutter app crashing while using flutter_pdfview package 为什么 Flutter 导入提供程序包不起作用? - Why is Flutter import provider package not working? flutter、kotlin gradle 使用位置 package 时出现问题 - flutter, kotlin gradle problem while using location package 使用 charts_flutter 包时,如何使用从提供程序文件获取的值设置条形的颜色 - How can i set the color of the bars with the values gotten from a provider file when using charts_flutter package listen:true 时在 flutter 中使用 Provider 的问题 - Problem in using Provider in flutter when listen:true 获取未处理的异常:“_CodecNotSupportedException”的实例”,同时使用 flutter_sound package - getting Unhandled Exception: Instance of '_CodecNotSupportedException'"while using flutter_sound package Flutter path_provider 在 Android 上出现错误,而在 iOS 上完美运行 - Flutter path_provider error on Android, while on iOS works perfectly 在实现以下设计时,我遇到了问题 - I'm facing problems while achieving the following design in flutter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM