跳转至

App State Management

Provider 黑夜模式案例

lib/main.dart

Dart
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: ChangeNotifierProvider(
          create: (context) => ThemeModel(),
          child: MyPage(),
        ),
      ),
    ),
  );
}

class ThemeModel extends ChangeNotifier {
  bool isDarkModeOn = false;

  void toggleDarkMode() {
    isDarkModeOn = !isDarkModeOn;
    notifyListeners();
  }
}

class MyPage extends StatelessWidget {
  MyPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Consumer<ThemeModel>(
      builder: (context, model, child) {
        return GestureDetector(
          onTap: () {
            model.toggleDarkMode();
          },
          child: Container(
            color: model.isDarkModeOn ? Colors.black : Colors.white,
            child: Center(
              child: Text(
                "Hello, world!",
                style: TextStyle(
                  color: model.isDarkModeOn ? Colors.white : Colors.black,
                  fontSize: 36,
                ),
              ),
            ),
          ),
        );
      },
    );
  }
}

References

  • https://docs.flutter.dev/development/data-and-backend/state-mgmt/simple