首页 > 解决方案 > Flutter - 更改默认字体“未定义的名称上下文”

问题描述

我正在尝试更改应用程序的默认字体主题,但它给了我一个错误,上面写着:

未定义的名称“上下文”。
尝试将名称更正为已定义的名称,或定义名称。

此行中的错误Theme.of(context).textTheme,是我的代码:

import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:nazar_mob/app_base/animations.dart';
import 'package:nazar_mob/pages/second_page.dart';
import 'package:nazar_mob/app_base/app_bar.dart';

void main() {
runApp(
    new MaterialApp(
    debugShowCheckedModeBanner: false,
    theme: ThemeData(
        textTheme: GoogleFonts.robotoCondensedTextTheme(
        Theme.of(context).textTheme,
        ),
    ),
    home: new MyFirstPage(),
    routes: <String, WidgetBuilder>{
        "/MySecondPage": (BuildContext context) => new MySecondPage()
    },
    )
);
}

标签: flutter

解决方案


您需要将您的 MaterialApp 包含在一个小部件中。小部件(无状态或有状态)提供了一个build功能,为您提供context

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        textTheme: GoogleFonts.robotoCondensedTextTheme(
        Theme.of(context).textTheme,
        ),
      ),
      home: new MyFirstPage(),
      routes: <String, WidgetBuilder>{
        "/MySecondPage": (BuildContext context) => new MySecondPage()
      },
    );
  }
}

推荐阅读