Flutter String格式化

flutter中没有直接提供字符串的格式化,可借助插件来进行格式化

1.在pubspec.yaml 文件中添加依赖

dependencies:
    sprintf: ^4.0.2

2.需要的文件中添加

import 'package:sprintf/sprintf.dart';

3.Demo

import 'package:flutter/material.dart';
import 'package:sprintf/sprintf.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('标题'),
      ),
      body: BodyPart(),
    );
  }
}

class BodyPart extends StatefulWidget {
  @override
  _BodyPartState createState() => _BodyPartState();
}

class _BodyPartState extends State {
  _BodyPartState();

  @override
  Widget build(BuildContext context) {
    String name = 'zhangsan';
    List pet = ['dog','cat'];
    String test = sprintf('his name is %s',[name]);
    String test2 = sprintf('%s has two pets %s and %s',[name,pet[0],pet[1]]);

    return Container(
      child: Text('$test\n$test2'),
    );
  }
}


4.效果


5001.jpg

你可能感兴趣的:(Flutter String格式化)