📌  相关文章
📜  Flutter – 使用 Material Design 创建时间选择器

📅  最后修改于: 2021-09-23 06:35:11             🧑  作者: Mango

时间选择器是一个 UI 组件,用于控制或允许选择 24 小时格式或 AM/PM 格式的时间。主要工作是简化时间选择过程并确保用户在应用程序中选择或选择有效时间。这可用于闹钟、秒表或任何其他需要时间选择的场景中。在原生 android 时间选择器中有两种模式可用,第一种是时钟,用户可以从时钟本身选择时间,首先选择房子,然后选择分钟。另一种模式是微调模式,用户可以在其中手动输入时间或滚动微调。 Flutter使这两种模式的实现变得非常容易,因为它开箱即用为我们提供了两种模式,而无需任何额外的努力。所以在本文中,我们将看到如何在flutter实现时间选择器。

我们将在此项目中使用 VS Code IDE,您也可以使用 Android Studio 或任何其他 IDE。此应用程序中将使用的唯一包是材料。dart。下面列出了开发此应用程序时将使用的一些概念:

  • 使用 Material Design 在屏幕上构建 UI。
  • 使用有状态小部件。
  • 通过dart函数构建逻辑。

第 1 步:第一步将很简单。

  • 在这里,我们首先导入了材料。 dart包将通过它在以下步骤中构建 UI。默认情况下, Flutter会使用 Material Design。材料设计系统是由谷歌创建的。尽管flutter为我们提供了完全的灵活性,可以根据我们的意愿或通过使用 Cupertino 小部件来定制设计,这些小部件是 Material Design 的替代品。
  • 然后我们初始化了main函数,它是这个flutter应用程序的起点。在main函数,我们有runApp方法。此方法的主要工作是膨胀给定的小部件并将其附加到屏幕上。要膨胀的小部件将在MyApp类中的以下步骤中进行描述。
Dart
import 'package:flutter/material.dart';
  
// Main function which starts the app
void main() {
  runApp(MyApp());
}


Dart
class MyApp extends StatelessWidget {
    
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
          
        // This is the theme of your application.
        primarySwatch: Colors.green,
      ),
      home: MyHomePage(title: 'GeeksForGeeks'),
    );
  }
}


Dart
class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  
  // This widget is the home of this app which is Stateful
  final String title;
  
  @override
  _MyHomePageState createState() => _MyHomePageState();
}


Dart
class _MyHomePageState extends State {
  TimeOfDay _time = TimeOfDay.now();
  TimeOfDay picked;
  
  Future selectTime(BuildContext context) async {
    picked = await showTimePicker(
      context: context,
      initialTime: _time,
    );
    setState(() {
      _time = picked;
  
      print(picked);
    });
  }
    
  ....


Dart
....
    
  @override
  Widget build(BuildContext context) {
    
    // This method is rerun every time setState is called.    
    return Scaffold(
      appBar: AppBar(
          
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
          
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            IconButton(
              iconSize: 80,
              icon: Icon(
                Icons.alarm,
                size: 80,
              ),
              onPressed: () {
                selectTime(context);
              },
            ),
            SizedBox(
              height: 60,
            ),
            Text('$_time', style: TextStyle(fontSize: 40)),
          ],
        ),
      ), 
    );
  }
}


Dart
import 'package:flutter/material.dart';
  
// Main function which starts the app
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
    
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
          
        // This is the theme of your application
        primarySwatch: Colors.green,
      ),
      home: MyHomePage(title: 'GeeksForGeeks'),
    );
  }
}
  
class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  
  // This widget is the home page of your application.
  final String title;
  
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
  
class _MyHomePageState extends State {
  TimeOfDay _time = TimeOfDay.now();
  TimeOfDay picked;
  
  Future selectTime(BuildContext context) async {
    picked = await showTimePicker(
      context: context,
      initialTime: _time,
    );
    setState(() {
      _time = picked;
  
      print(picked);
    });
  }
  
  @override
  Widget build(BuildContext context) {
      
    // This method is rerun every time setState is called.
    return Scaffold(
      appBar: AppBar(
          
        // Here we take the value from the 
        // MyHomePage object that was created by
        // the App.build method, and use it
        // to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
          
        // Center is a layout widget. It takes
        // a single child and positions it
        // in the middle of the parent.
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            IconButton(
              iconSize: 80,
              icon: Icon(
                Icons.alarm,
                size: 80,
              ),
              onPressed: () {
                selectTime(context);
              },
            ),
            SizedBox(
              height: 60,
            ),
            Text('$_time', style: TextStyle(fontSize: 40)),
          ],
        ), // Column
      ), // Center
    ); // Scaffold
  }
}


第 2 步:在这一步中,我们执行了三项主要工作。

  • 这里将保存此应用程序的所有小部件的MyApp类扩展为不需要可变状态的无状态小部件。
  • 然后覆盖无状态小部件已经存在的信息,我们提供了我们自己的相同描述。
  • 下面我们使用了 build 方法。这描述了此小部件表示的用户界面部分。并且还控制要在屏幕上绘制的小部件的位置。在这里面,我们已经描述了MaterialApp标题、主题和扩展类

Dart

class MyApp extends StatelessWidget {
    
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
          
        // This is the theme of your application.
        primarySwatch: Colors.green,
      ),
      home: MyHomePage(title: 'GeeksForGeeks'),
    );
  }
}

第 3 步:第 3步中,我们有以下内容:

  • 此小部件是您的应用程序的主页。它是有状态的,这意味着它有一个 State 对象(定义如下),其中包含影响其外观的字段。
  • 这个类是状态的配置。它保存由父级(在本例中为 App 小部件)提供并由 State 的 build 方法使用的值(在本例中为标题)。 Widget 子类中的字段始终标记为“final”。

Dart

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  
  // This widget is the home of this app which is Stateful
  final String title;
  
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

第 4 步:在这一步中,我们构建时间选择的逻辑。

  • 我们有TimeofDay类,它代表一天中的时间,与当天可能落在的日期或时区无关。时间由 [小时] 和 [分钟] 对表示。一旦创建,这两个值就无法更改。通过使用这个类,我们将创建由 UI 选择器选择的一天中的时间。 TimeOfDay.now()创建基于当前时间的时间基准。这将小时和分钟设置为当前时间。
  • 然后在Future 中,我们使用了showTimePicker函数,它会在屏幕上显示一个材质设计的时间选择器,供用户选择时间。 setState函数告诉系统对象状态中的某些内容已更改。它选择的时间设置为等于选择的时间,然后打印在控制台上。

Dart

class _MyHomePageState extends State {
  TimeOfDay _time = TimeOfDay.now();
  TimeOfDay picked;
  
  Future selectTime(BuildContext context) async {
    picked = await showTimePicker(
      context: context,
      initialTime: _time,
    );
    setState(() {
      _time = picked;
  
      print(picked);
    });
  }
    
  ....

第 5 步:在这一步中,我们通过为逻辑构建 UI 来完成应用程序,这是在上一步中策划的。

  • MyHomePage类中,我们有build方法,每当用户选择时间时都会返回该方法,因为它将调用setState函数。
  • 以下是Scaffold小部件,它包含显示在屏幕上的所有小部件,例如位于屏幕顶部的AppBar和包含应用程序主体Center小部件。在Center小部件中,我们有由SizedBox分隔的IconButtonText
  • 每当按下闹钟图标时, selectTime函数就会被触发,它会弹出一个时间选择器。

Dart

....
    
  @override
  Widget build(BuildContext context) {
    
    // This method is rerun every time setState is called.    
    return Scaffold(
      appBar: AppBar(
          
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
          
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            IconButton(
              iconSize: 80,
              icon: Icon(
                Icons.alarm,
                size: 80,
              ),
              onPressed: () {
                selectTime(context);
              },
            ),
            SizedBox(
              height: 60,
            ),
            Text('$_time', style: TextStyle(fontSize: 40)),
          ],
        ),
      ), 
    );
  }
}

完整代码:

Dart

import 'package:flutter/material.dart';
  
// Main function which starts the app
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
    
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
          
        // This is the theme of your application
        primarySwatch: Colors.green,
      ),
      home: MyHomePage(title: 'GeeksForGeeks'),
    );
  }
}
  
class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  
  // This widget is the home page of your application.
  final String title;
  
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
  
class _MyHomePageState extends State {
  TimeOfDay _time = TimeOfDay.now();
  TimeOfDay picked;
  
  Future selectTime(BuildContext context) async {
    picked = await showTimePicker(
      context: context,
      initialTime: _time,
    );
    setState(() {
      _time = picked;
  
      print(picked);
    });
  }
  
  @override
  Widget build(BuildContext context) {
      
    // This method is rerun every time setState is called.
    return Scaffold(
      appBar: AppBar(
          
        // Here we take the value from the 
        // MyHomePage object that was created by
        // the App.build method, and use it
        // to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
          
        // Center is a layout widget. It takes
        // a single child and positions it
        // in the middle of the parent.
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            IconButton(
              iconSize: 80,
              icon: Icon(
                Icons.alarm,
                size: 80,
              ),
              onPressed: () {
                selectTime(context);
              },
            ),
            SizedBox(
              height: 60,
            ),
            Text('$_time', style: TextStyle(fontSize: 40)),
          ],
        ), // Column
      ), // Center
    ); // Scaffold
  }
}

输出:

想要一个更快节奏和更具竞争力的环境来学习 Android 的基础知识吗?
单击此处前往由我们的专家精心策划的指南,旨在让您立即做好行业准备!