将shared_preferences添加到provider_counter(ChangeNotifier)示例应用程序会导致“无法分配参数类型‘Future<SharedPreferences>’”

问题描述 投票:0回答:1

我正在尝试修改 provider_counter 示例以使用共享首选项。

final prefs = SharedPreferences.getInstance();

void main() {
  var prefs = SharedPreferences.getInstance();
  runApp(
    ChangeNotifierProvider(
      create: (context) => Counter(prefs: prefs),
      child: const MyApp(),
    ),
  );
}

// ...

class Counter with ChangeNotifier {
  int value = 0;
  final SharedPreferences prefs;

  Counter({required this.prefs}) {
    value = prefs.getInt('counter') ?? 0;
  }

  void _setPrefItems() {
    prefs.setInt('counter', value);
  }

  void increment() {
    value += 1;
    _setPrefItems();
    notifyListeners();
  }
}

但是,我收到错误:

The argument type 'Future<SharedPreferences>' can't be assigned to the parameter type 'SharedPreferences'

flutter
1个回答
0
投票

我按照这个answer的建议,通过用 Future 包装主函数来解决这个问题:

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

final prefs = SharedPreferences.getInstance();

Future<void> main() async {
  var prefs = await SharedPreferences.getInstance();
  runApp(
    ChangeNotifierProvider(
      create: (context) => Counter(prefs: prefs),
      child: const MyApp(),
    ),
  );
}

class Counter with ChangeNotifier {
  int value = 0;
  final SharedPreferences prefs;

  Counter({required this.prefs}) {
    value = prefs.getInt('counter') ?? 0;
  }

  void _setPrefItems() {
    prefs.setInt('counter', value);
  }

  void increment() {
    value += 1;
    _setPrefItems();
    notifyListeners();
  }
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter Demo Home Page'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Text('You have pushed the button this many times:'),
            Consumer<Counter>(
              builder: (context, counter, child) => Text(
                '${counter.value}',
                style: Theme.of(context).textTheme.headlineMedium,
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          var counter = context.read<Counter>();
          counter.increment();
        },
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.