flutter MultiProvider位于main中,而不是位于树中

3lxsmp7m  于 2023-01-27  发布在  Flutter
关注(0)|答案(2)|浏览(112)

在main中插入所有提供程序是否会影响性能?将各个提供程序放在树中间需要它们的位置是否是更好的选择?

esyap4oy

esyap4oy1#

在大型应用程序中注入许多值时,Provider可能会迅速变得非常嵌套:

Provider<Something>(
  create: (_) => Something(),
  child: Provider<SomethingElse>(
    create: (_) => SomethingElse(),
    child: Provider<AnotherThing>(
      create: (_) => AnotherThing(),
      child: someWidget,
    ),
  ),
),

收件人:

MultiProvider(
  providers: [
    Provider<Something>(create: (_) => Something()),
    Provider<SomethingElse>(create: (_) => SomethingElse()),
    Provider<AnotherThing>(create: (_) => AnotherThing()),
  ],
  child: someWidget,
)

**

这两个示例的行为完全相同。MultiProvider只更改代码的外观。

**

mftmpeh8

mftmpeh82#

试试这个

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

import 'models/model_provider.dart';
import 'modules/screen_root.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return statemanagement.MultiProvider(
      providers: [
        statemanagement.Provider<ModelProvider>(
          create: ((_) => ModelProvider())),
        ],
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        title: 'Flutter Multi Provider',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: const ScreenRoot(),
      ),
    );
  }
}

相关问题