Widget 不会在监听 Flutter Provider 暴露的值时重新构建。

huangapple go评论67阅读模式
英文:

Widget will not rebuild when listening to the value of Flutter Provider exposed

问题

以下是您要翻译的代码部分:

在我的代码中,我将使用Provider.value将一个值暴露给MyHomePage,同时,MyHomePage将使用Provider来获取该值,监听设置为true。如果我在外部更改该值,MyHomePage将不会重新构建,似乎监听不起作用。

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

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

int _counter = 0;

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Provider.value(
        value: _counter,
        child: MyHomePage(),
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);
  void _incrementCounter() {
    _counter++;
  }

  @override
  Widget build(BuildContext context) {
    print('build');
    int value = Provider.of<int>(
      context,
      listen: true,
    );
    return Scaffold(
      appBar: AppBar(
        title: Text('123'),
      ),
      body: Center(
        child: Text('value:${value}'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}
英文:

In my code I will use Provider.value to expose a value to MyHomePage ,at the same time ,the MyHomePage will use Provider to get the value with the listen set to true,If i change the value outside , the MyHomePage will not rebuild , seems the listenning not working .

import &#39;package:flutter/material.dart&#39;;
import &#39;package:provider/provider.dart&#39;;

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

int _counter = 0;

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: &#39;Flutter Demo&#39;,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Provider.value(
        value: _counter,
        child: MyHomePage(),
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);
  void _incrementCounter() {
    _counter++;
  }

  @override
  Widget build(BuildContext context) {
    print(&#39;build&#39;);
    int value = Provider.of&lt;int&gt;(
      context,
      listen: true,
    );
    return Scaffold(
      appBar: AppBar(
        title: Text(&#39;123&#39;),
      ),
      body: Center(
        child: Text(&#39;value:${value}&#39;),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: &#39;Increment&#39;,
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

答案1

得分: 1

Here are the translated code portions:

第一部分:

你需要使用一个模型,它会通知其监听器,如果你希望你的小部件重建。 `Provider` 没有办法知道你增加了 `_counted`。

请对代码进行以下更改,使用 `ValueNotifier<int>` 代替 `int`(你还需要将 `Provider` 替换为 `ChangeNotifierProvider`):

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

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

final _counter = ValueNotifier<int>(0); // <- 这里

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

  // 这个小部件是你应用程序的根。
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: ChangeNotifierProvider.value(
        value: _counter,
        child: MyHomePage(),
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);
  void _incrementCounter() {
    _counter.value++;
  }

  @override
  Widget build(BuildContext context) {
    print('build');
    int value = Provider.of<ValueNotifier<int>>(
      context,
      listen: true,
    ).value;
    return Scaffold(
      appBar: AppBar(
        title: Text('123'),
      ),
      body: Center(
        child: Text('value:${value}'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

第二部分:

更好的方式是不使用静态全局变量和 `ChangeNotifierProvider.value`,而是使用 `ChangeNotifierProvider.new`。

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

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

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

  // 这个小部件是你应用程序的根。
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      // 这里:
      home: ChangeNotifierProvider(
        create: (context) => ValueNotifier<int>(0),
        child: MyHomePage(),
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);
  void _incrementCounter(BuildContext context) {
    context.read<ValueNotifier<int>>().value++;
  }

  @override
  Widget build(BuildContext context) {
    print('build');
    int value = Provider.of<ValueNotifier<int>>(
      context,
      listen: true,
    ).value;
    return Scaffold(
      appBar: AppBar(
        title: Text('123'),
      ),
      body: Center(
        child: Text('value:${value}'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => _incrementCounter(context),
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

如果需要进一步的说明或有其他翻译,请告诉我。

英文:

You need to use a model that would notify its listeners if you want your widgets to rebuild. Provider has no way to know you incremented _counted.

Do those code changes to use ValueNotifier&lt;int&gt; instead of int (you will also need to replace Provider with ChangeNotifierProvider):

import &#39;package:flutter/material.dart&#39;;
import &#39;package:provider/provider.dart&#39;;

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

final _counter = ValueNotifier&lt;int&gt;(0); // &lt;- Here

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: &#39;Flutter Demo&#39;,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: ChangeNotifierProvider.value(
        value: _counter,
        child: MyHomePage(),
      ),

    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);
  void _incrementCounter() {
    _counter.value++;
  }

  @override
  Widget build(BuildContext context) {
    print(&#39;build&#39;);
    int value = Provider.of&lt;ValueNotifier&lt;int&gt;&gt;(
      context,
      listen: true,
    ).value;
    return Scaffold(
      appBar: AppBar(
        title: Text(&#39;123&#39;),
      ),
      body: Center(
        child: Text(&#39;value:${value}&#39;),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: &#39;Increment&#39;,
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

It would be better to not use a static global variable and ChangeNotifierProvider.value but ChangeNotifierProvider.new instead.

import &#39;package:flutter/material.dart&#39;;
import &#39;package:provider/provider.dart&#39;;

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


class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: &#39;Flutter Demo&#39;,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      // Here:
      home: ChangeNotifierProvider(
        create: (context) =&gt; ValueNotifier&lt;int&gt;(0),
        child: MyHomePage(),
      ),

    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);
  void _incrementCounter(BuildContext context) {
    context.read&lt;ValueNotifier&lt;int&gt;&gt;().value++;
  }

  @override
  Widget build(BuildContext context) {
    print(&#39;build&#39;);
    int value = Provider.of&lt;ValueNotifier&lt;int&gt;&gt;(
      context,
      listen: true,
    ).value;
    return Scaffold(
      appBar: AppBar(
        title: Text(&#39;123&#39;),
      ),
      body: Center(
        child: Text(&#39;value:${value}&#39;),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: &#39;Increment&#39;,
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

huangapple
  • 本文由 发表于 2023年5月25日 16:18:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76330220.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定