Flutter扩展功能插件flutter_extensions的使用

发布于 1周前 作者 ionicwang 来自 Flutter

Flutter扩展功能插件flutter_extensions的使用

Flutter Extensions

Widgets

Widgets Description
AspectRatioBuilder 使用宽高比构建小部件
FixedIndexedStack 当索引被选中时才构建子项
InkStack 在图像上添加[InkWell]
KeyboardRemover 当用户按屏幕时关闭键盘
SizeCopier 将小部件尺寸复制到SizeCopierController
SizeCopy 将小部件尺寸读取到SizeCopierController并构建子项
FillSingleChildScrollView 允许在滚动视图中使用flex小部件

Enums

Enums
TargetPlatform
AppLifecycleState

BuildContext

Command Description
theme 从最近的上下文中获取ThemeData实例
defaultTextStyle 从最近的上下文中获取DefaultTextStyle实例
iconTheme 从最近的上下文中获取IconThemeData实例
localizations 从最近的上下文中获取Localizations实例
locale 从最近的上下文中获取Locale实例
navigator 从最近的上下文中获取Navigator实例
tryRead 如果存在则返回读取的值,否则返回null
tryWatch 如果存在则返回观察的值,否则返回null

DateTime - Time

Command Description
DateTime.toTimeOfDay 转换为[TimeOfDay]
DateTime.copyWithTimeOfDay 复制带有[timeOfDay]

Size

Command Description
copyWith 使用新值进行复制

InputDecoration

Command Description
InputDecoration.completeWith(…) 完成属性后返回InputDecoration的副本

Table

Command Description
DataRow.copyWith(…) 返回带有新属性的DataRow的副本
DataRow.completeWith(…) 完成属性后返回DataRow的副本
DataCell.copyWith(…) 返回带有新属性的DataCell的副本
DataCell.completeWith(…) 完成属性后返回DataCell的副本

Listenable - ChangeNotifier

Widget Description
ChangeableProvider
ChangeableBuilder 监听Listenable并在更改时构造UI
ChangeableListener
ChangeableConsumer 待办…
ChangeableValueBuilder 监听Listenable并在更改时构造UI,仅当更改符合条件或值不改变时
ChangeableValueListener 待办…
ChangeableValueConsumer 待办…

RxStream

监听StreamStreamValue并过滤先前和当前状态 不重复数据或AsyncSnapshot

Widget Description
RxStreamConsumer 根据AsyncSnapshot构建小部件并通知AsyncSnapshot更改
RxStreamBuilder 根据AsyncSnapshot构建小部件
RxStreamListener 通知AsyncSnapshot更改
ValueStreamConsumer 根据数据构建小部件并通知数据更改
ValueStreamBuilder 根据数据构建小部件
ValueStreamListener 通知数据更改

示例代码

AspectRatioBuilder

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

class AspectRatioExample extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('AspectRatioBuilder Example')),
      body: Center(
        child: AspectRatioBuilder(
          aspectRatio: 16 / 9,
          builder: (context, size) {
            return Container(
              width: size.width,
              height: size.height,
              color: Colors.blue,
            );
          },
        ),
      ),
    );
  }
}

FixedIndexedStack

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

class FixedIndexedStackExample extends StatelessWidget {
  final int selectedIndex = 0;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('FixedIndexedStack Example')),
      body: Center(
        child: FixedIndexedStack(
          index: selectedIndex,
          children: [
            Container(color: Colors.red, width: 100, height: 100),
            Container(color: Colors.green, width: 100, height: 100),
            Container(color: Colors.blue, width: 100, height: 100),
          ],
        ),
      ),
    );
  }
}

InkStack

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

class InkStackExample extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('InkStack Example')),
      body: Center(
        child: InkStack(
          onTap: () {
            print("Image Tapped");
          },
          child: Image.network(
            'https://example.com/image.png',
            fit: BoxFit.cover,
          ),
        ),
      ),
    );
  }
}

KeyboardRemover

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

class KeyboardRemoverExample extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('KeyboardRemover Example')),
      body: GestureDetector(
        onTap: () {
          FocusScope.of(context).unfocus();
        },
        child: Center(
          child: Text('Tap to remove keyboard'),
        ),
      ),
    );
  }
}

SizeCopier

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

class SizeCopierExample extends StatefulWidget {
  [@override](/user/override)
  _SizeCopierExampleState createState() => _SizeCopierExampleState();
}

class _SizeCopierExampleState extends State<SizeCopierExample> {
  SizeCopierController _controller = SizeCopierController();

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('SizeCopier Example')),
      body: Column(
        children: [
          SizeCopier(
            controller: _controller,
            child: Container(
              width: 100,
              height: 100,
              color: Colors.red,
            ),
          ),
          Container(
            width: _controller.size?.width,
            height: _controller.size?.height,
            color: Colors.blue,
          ),
        ],
      ),
    );
  }
}

SizeCopy

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

class SizeCopyExample extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('SizeCopy Example')),
      body: SizeCopy(
        builder: (context, size) {
          return Container(
            width: size.width,
            height: size.height,
            color: Colors.green,
          );
        },
      ),
    );
  }
}

ChangeableBuilder

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

class ChangeableBuilderExample extends StatefulWidget {
  [@override](/user/override)
  _ChangeableBuilderExampleState createState() =>
      _ChangeableBuilderExampleState();
}

class _ChangeableBuilderExampleState extends State<ChangeableBuilderExample>
    with ChangeNotifier {
  int counter = 0;

  void increment() {
    counter++;
    notifyListeners();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('ChangeableBuilder Example')),
      body: ChangeableBuilder<int>(
        listenable: this,
        builder: (context, value) {
          return Center(
            child: Text('Counter: $value'),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: increment,
        child: Icon(Icons.add),
      ),
    );
  }
}

RxStreamBuilder

import 'package:flutter/material.dart';
import 'package:flutter_extensions/flutter_extensions.dart';
import 'package:rxdart/rxdart.dart';

class RxStreamBuilderExample extends StatelessWidget {
  final Stream<int> _stream = BehaviorSubject<int>.seeded(0);

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('RxStreamBuilder Example')),
      body: Center(
        child: RxStreamBuilder<int>(
          stream: _stream,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return Text('Current Value: ${snapshot.data}');
            } else {
              return Text('Loading...');
            }
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          _stream.sink.add(_stream.value + 1);
        },
        child: Icon(Icons.add),
      ),
    );
  }
}

更多关于Flutter扩展功能插件flutter_extensions的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter扩展功能插件flutter_extensions的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,flutter_extensions 并不是一个官方或广泛认可的 Flutter 插件名称,但基于你的问题,我会假设你指的是一种机制或一系列插件,用于扩展 Flutter 应用的功能。在 Flutter 社区中,有许多第三方插件可以帮助你实现各种功能,比如相机访问、位置服务、文件存储等。

为了给你一个具体的代码示例,我将使用几个常见的 Flutter 插件来展示如何扩展 Flutter 应用的功能。这些插件包括 camerageolocatorpath_provider

1. 添加依赖

首先,在你的 pubspec.yaml 文件中添加这些插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  camera: ^0.9.4+5  # 请检查最新版本号
  geolocator: ^8.0.1  # 请检查最新版本号
  path_provider: ^2.0.8  # 请检查最新版本号

然后运行 flutter pub get 来获取这些依赖。

2. 使用相机插件

以下是一个简单的示例,展示如何使用 camera 插件来访问设备的相机:

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

List<CameraDescription> cameras;

Future<void> main() async {
  // 获取可用的相机列表
  cameras = await availableCameras();
  runApp(MyApp());
}

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

class CameraApp extends StatefulWidget {
  @override
  _CameraAppState createState() => _CameraAppState();
}

class _CameraAppState extends State<CameraApp> {
  CameraController? controller;

  @override
  void initState() {
    super.initState();
    if (cameras.isEmpty) {
      return;
    }
    controller = CameraController(
      cameras[0],
      ResolutionPreset.medium,
    )..initialize().then((_) {
      if (!mounted) {
        return;
      }
      setState(() {});
    });
  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (controller == null || !controller!.value.isInitialized) {
      return Container();
    }
    return Scaffold(
      appBar: AppBar(
        title: Text('Camera'),
      ),
      body: CameraPreview(controller!),
    );
  }
}

3. 使用地理定位插件

以下是一个使用 geolocator 插件来获取当前位置的示例:

import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:geolocator_platform_interface/geolocator_platform_interface.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Geolocation'),
        ),
        body: Center(
          child: FutureBuilder<Position>(
            future: _getCurrentLocation(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                if (snapshot.hasError) {
                  return Text('Error: ${snapshot.error}');
                } else {
                  return Text(
                    'Latitude: ${snapshot.data?.latitude}, Longitude: ${snapshot.data?.longitude}',
                  );
                }
              } else {
                return CircularProgressIndicator();
              }
            },
          ),
        ),
      ),
    );
  }

  Future<Position> _getCurrentLocation() async {
    bool serviceEnabled;
    LocationPermission permission;

    // 检查位置服务是否启用
    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      return Future.error('Location services are disabled.');
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        return Future.error('Location permissions are denied');
      }
    }
    if (permission == LocationPermission.deniedForever) {
      // 处理权限被永久拒绝的情况
      return Future.error(
          'Location permissions are permanently denied, we cannot request permissions.');
    }

    // 获取当前位置
    return await Geolocator.getCurrentPosition(
      desiredAccuracy: LocationAccuracy.high,
    );
  }
}

4. 使用路径提供者插件

以下是一个使用 path_provider 插件来获取应用文档目录路径的示例:

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Path Provider'),
        ),
        body: Center(
          child: FutureBuilder<String>(
            future: _getApplicationDocumentsDirectory(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                if (snapshot.hasError) {
                  return Text('Error: ${snapshot.error}');
                } else {
                  return Text('Application documents directory: ${snapshot.data}');
                }
              } else {
                return CircularProgressIndicator();
              }
            },
          ),
        ),
      ),
    );
  }

  Future<String> _getApplicationDocumentsDirectory() async {
    final directory = await getApplicationDocumentsDirectory();
    return directory.path;
  }
}

这些示例展示了如何使用 Flutter 插件来扩展应用的功能。根据你的具体需求,你可以进一步自定义和扩展这些功能。

回到顶部