0

我无法使用从其他文件导入的导入自定义小部件中的 ThemeData,我不知道 BuildContext 是否正在更改或什么。对于 main.dart 文件中使用的所有小部件,他们可以轻松使用 Theme.of(context).colorScheme.primary 但从导入的小部件中这不起作用。

main.dart

import 'package:flutter/material.dart';

import 'widgets/expenses_list.dart';
import 'models/expenses_model.dart';
import 'widgets/new_expense.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData().copyWith(
        colorScheme: ThemeData().colorScheme.copyWith(primary: Colors.red),
      ),
      home: MyAppPage(),
    );
  }
}

class MyAppPage extends StatefulWidget {
  @override
  _MyAppPageState createState() => _MyAppPageState();
}

class _MyAppPageState extends State<MyAppPage> {
  final List<ExpensesModel> _expensesObjectList = [
    ExpensesModel(
      id: DateTime.now().toString(),
      name: "Shoes",
      amount: 1200,
      date: DateTime.now(),
    ),
    ExpensesModel(
      id: DateTime.now().toString(),
      name: "Gun",
      amount: 120000,
      date: DateTime.now(),
    ),
  ];

  void _addExpense(String exTitle, double exAmount) {
    final _addExpenseObject = ExpensesModel(
      id: DateTime.now().toString(),
      name: exTitle,
      amount: exAmount,
      date: DateTime.now(),
    );
    setState(() {
      _expensesObjectList.add(_addExpenseObject);
    });
  }

  void _startAddNewExpense(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (bcontext) {
          return NewExpense(_addExpense);
        });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          backgroundColor: Theme.of(context).colorScheme.primary,
          // HERE IT DOES WORK
          title: Text(
            "Expense App",
            // style: Theme.of(context).textTheme.title,
          ),
          actions: [
            IconButton(
              onPressed: () {
                _startAddNewExpense(context);
              },
              icon: Icon(Icons.add),
            ),
          ],
        ),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Card(
              elevation: 5,
              color: Theme.of(context).colorScheme.primary,
              // HERE IT DOES WORK
              child: Text("CHART!!"),
            ),
            ExpensesList(_expensesObjectList), //THE IMPORTED WIDGET
          ],
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            _startAddNewExpense(context);
          },
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}

导入的小部件

import 'package:flutter/material.dart';

import '../models/expenses_model.dart';

class ExpensesList extends StatelessWidget {
  final List<ExpensesModel> expensesObjectList;

  ExpensesList(this.expensesObjectList);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 600,
      child: ListView.builder(
        itemBuilder: (context, index) {
          return Card(
            elevation: 5,
            child: Row(
              children: [
                Container(
                  padding: EdgeInsets.symmetric(
                    vertical: 10,
                    horizontal: 10,
                  ),
                  margin: EdgeInsets.all(10),
                  decoration: BoxDecoration(
                    border: Border.all(
                      color: Theme.of(context).colorScheme.primary,
                      // HERE IT DOES NOT WORK
                      width: 2,
                    ),
                  ),
                  child: Text(
                    "PKR ${expensesObjectList[index].amount}",
                    style: TextStyle(
                      color: Theme.of(context).colorScheme.primary,
                      // HERE IT DOES NOT WORK
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      "${expensesObjectList[index].name}",
                      style:
                          TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                    ),
                    Text(
                      DateTime.now().toString(),
                      style: TextStyle(
                        color: Colors.grey,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          );
        },
        itemCount: expensesObjectList.length,
      ),
    );
  }
}

应用截图

如您所见,边框和文本没有使用主题定义的红色颜色。

4

2 回答 2

0

您可以通过以下方式访问您应用的 ThemeData。

Color color = Theme.of(context).primaryColor;
于 2021-08-21T09:57:56.330 回答
0

我认为“类_MyAppPageState”中的“build”不必要的“MaterialApp”,就像这样。

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      backgroundColor: Theme.of(context).colorScheme.primary,
      // HERE IT DOES WORK
      title: Text(
        "Expense App",
        // style: Theme.of(context).textTheme.title,
      ),
      actions: [
        IconButton(
          onPressed: () {
            _startAddNewExpense(context);
          },
          icon: Icon(Icons.add),
        ),
      ],
    ),
    body: Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Card(
          elevation: 5,
          color: Theme.of(context).colorScheme.primary,
          // HERE IT DOES WORK
          child: Text("CHART!!"),
        ),
        ExpensesList(_expensesObjectList), //THE IMPORTED WIDGET
      ],
    ),
    floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
    floatingActionButton: FloatingActionButton(
      onPressed: () {
        _startAddNewExpense(context);
      },
      child: Icon(Icons.add),
    ),
  );
}

如果你真的需要“类_MyAppPageState”的“MaterialApp”,我想你可以添加主题属性,像这样。

@override
Widget build(BuildContext context) {
  return MaterialApp(
    debugShowCheckedModeBanner: false,
    theme: Theme.of(context), // <- add this line.
    home: Scaffold(

顺便说一句,你为什么不使用primarySwatch?
这个怎么样?

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.red,
      ),
      home: MyAppPage(),
    );
  }
}

在此处输入图像描述

于 2021-08-21T13:57:03.370 回答