风格化

风格化

如何设置组件的风格?

在 React Native 中,内联风格化和 stylesheets.create 可以用于设置组件的风格。

// React Native
<View style={styles.container}>
  <Text style={{ fontSize: 32, color: 'cyan', fontWeight: '600' }}>
    This is a sample text
  </Text>
</View>

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center'
  }
});

在 Flutter 中, Text widget 可以接受 TextStyle 作为它的风格化属性。如果你想在不同的场合使用相同的文本风格,你可以创建一个 TextStyle 类,并且在多个 Text widget 中使用它。

// Flutter
var textStyle = TextStyle(fontSize: 32.0, color: Colors.cyan, fontWeight:
   FontWeight.w600);
    ...
Center(
  child: Column(
    children: <Widget>[
      Text(
        'Sample text',
        style: textStyle,
      ),
      Padding(
        padding: EdgeInsets.all(20.0),
        child: Icon(Icons.lightbulb_outline,
          size: 48.0, color: Colors.redAccent)
      ),
    ],
  ),
)

Styling on Android Android

Styling on iOS iOS

我如何使用 Icons 和 Colors 呢?

React Native 并不包含默认图标,所以需要使用第三方库。

在 Flutter 中,引用 Material 库的时候就同时引入了 Material icons和 colors。

Icon(Icons.lightbulb_outline, color: Colors.redAccent)

When using the Icons class, make sure to set uses-material-design: true inthe project’s pubspec.yaml file. This ensures thatthe MaterialIcons font, which displays the icons, is included in your app.

name: my_awesome_application
flutter: uses-material-design: true

当使用 Icons 类时,确保在项目的 pubspec.yaml 文件中设置 uses-material-design: true。这样保证 MaterialIcons 相关字体被包含在你的应用中。

name: my_awesome_application
flutter: uses-material-design: true

Flutter 的 Cupertino (iOS-style) 包为 iOS 设计语言提供高分辨率的 widget。要使用 CupertinoIcons 字体,在项目的 pubspec.yaml 文件中添加 cupertino_icons 的依赖即可。

name: my_awesome_application
dependencies:
  cupertino_icons: ^0.1.0

要在全局范围内自定义组件的颜色和风格,使用 ThemeData 为不同的主题指定默认颜色。在 MaterialApp 的主题属性中设置 ThemeData 对象。Colors 类提供 Material Design colorpalette 中所提供的颜色配置。

下面的示例代码将主色调设置为 blue 然后文本颜色设置为 red。

class SampleApp extends StatelessWidget {
  @override
 widget build(BuildContext context) {
    return MaterialApp(
      title: 'Sample App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        textSelectionColor: Colors.red
      ),
      home: SampleAppPage(),
    );
  }
}

如何增加风格化主题?

在 React Native,常用主题都定义在 stylesheets 中。

在 Flutter 中,为所有组件创建统一风格可以在 ThemeData 类中定义,并将它赋值给 MaterialApp 的主题属性。

  @override
 widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primaryColor: Colors.cyan,
        brightness: Brightness.dark,
      ),
      home: StylingPage(),
    );
  }

Theme 可以在不使用 MaterialApp widget 的情况下使用。Theme 接受一个 ThemeData 参数,并且将 ThemeData 应用于它的全部子 widget。

 @override
 widget build(BuildContext context) {
    return Theme(
      data: ThemeData(
        primaryColor: Colors.cyan,
        brightness: brightness,
      ),
      child: Scaffold(
         backgroundColor: Theme.of(context).primaryColor,
              ...
              ...
      ),
    );
  }