Flutter-如何在一个文件“ text_style.dart”函数中管理TextStyle以在另一视图中调用?

时间:2019-07-05 07:05:45

标签: flutter dart

我想用一些构造函数(例如Color和fontWeight)创建一个自定义TextStyle,因此稍后在屏幕视图中,字体和大小的样式是固定的,但是只能自定义颜色和fontweight。

    class TextStyles {
  final Color fontColor;

  const TextStyles({
    this.fontColor = Colors.black;
  });

  static const TextStyle buttonText = const TextStyle(
      fontFamily: 'Montserrat',
      color: fontColor,
      fontWeight: FontWeight.w700,
      fontSize: 14.0
  );
}

class CustomButton extends StatelessWidget {
  ....
  final Function onPressed;

  const CustomButton({
    Key key,
   ...
    @required this.onPressed,
    this.textSize = 14.0,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final CreateBlueButton = FlatButton(
        color: background,
        child: Text(
          text,
          style: TextStyleCustom,
        )
    );

    return Container(
      constraints: BoxConstraints.expand(height: 53),
      ...

2 个答案:

答案 0 :(得分:1)

这是您需要的:

import 'package:flutter/material.dart';

class MyTextStyle extends TextStyle {
  final Color color;
  final FontWeight fontWeight;
  final double size;
  final String fontFamily;

  const MyTextStyle({
    @required this.color,
    @required this.fontWeight,
    this.size = 14,
    this.fontFamily = 'Montserrat',
  })  : assert(color != null && fontWeight != null),
        super(
          color: color,
          fontWeight: fontWeight,
          fontSize: size,
          fontFamily: fontFamily,
        );
}

答案 1 :(得分:0)

我使用的方法是:

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

class MyApp extends StatelessWidget {

  MyApp() {
    SystemChrome.setSystemUIOverlayStyle(
      SystemUiOverlayStyle(
        statusBarColor: Colors.white
      )
    );
  }

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: _configureThemeData(),
      home: LoginScreen(),
    );
  }

  ThemeData _configureThemeData() {
    return ThemeData(
        textTheme: TextTheme(
            headline: TextStyle(
                fontSize: 35.0,
                height: 0.8,
                color: Colors.red,
                fontWeight: FontWeight.w700),
            title: TextStyle(fontSize: 35),
            subtitle: TextStyle(
              fontSize: 20,
              color: Colors.grey,
            ),
            body1: TextStyle(fontSize: 15, color: Colors.white),
            body2: TextStyle(fontSize: 12, color: Colors.white)));
  }
}

,然后使用以下命令调用此文字样式:

Text('I AM HEADLINE IN STYLE',
                style: Theme.of(context).textTheme.headline)