Flutter常见库使用

发布时间 2023-12-27 18:58:36作者: ZhangShengjie

1、网络库 dio

dio: ^5.4.0

import 'package:dio/dio.dart';

final dio = Dio();

void getHttp() async {
  final response = await dio.get('https://dart.dev');
  print(response);
}

2、JSON解析

json_serializable: ^6.7.1 
json_annotation: ^4.8.1
build_runner: ^2.4.7
新建一个模型 test_model.dart
import 'package:json_annotation/json_annotation.dart';
part 'test_model.g.dart';

@JsonSerializable()
class TestModel {
  String name = "";
  int age = 0;
  double height = 0;

  TestModel({required this.name, required this.age, required this.height});

  factory TestModel.fromJson(Map<String, dynamic> json) => _$TestModelFromJson(json);

  Map<String, dynamic> toJson() => _$TestModelToJson(this);
}

终端执行 

dart run build_runner build

3、获取文件路径

path_provider: ^2.1.1

 void _downlodUrl() async {
    var url = 'https://sample-videos.com/video123/flv/240/big_buck_bunny_240p_10mb.flv';
    var path = await getDownloadsDirectory();
    print("ios paht:$path");
    String savePath = "${path?.path}/temp.mp4";
    print(savePath);
    Dio().download(url, savePath,onReceiveProgress: (c,t) {
      var progress = "${(c / t * 100)}%";
    print(progress);
    });
  }

4、数据存储

shared_preferences: ^2.2.2

// Obtain shared preferences.
final SharedPreferences prefs = await SharedPreferences.getInstance();

// Save an integer value to 'counter' key.
await prefs.setInt('counter', 10);
// Save an boolean value to 'repeat' key.
await prefs.setBool('repeat', true);
// Save an double value to 'decimal' key.
await prefs.setDouble('decimal', 1.5);
// Save an String value to 'action' key.
await prefs.setString('action', 'Start');
// Save an list of strings to 'items' key.
await prefs.setStringList('items', <String>['Earth', 'Moon', 'Sun']);

//获取

// Try reading data from the 'counter' key. If it doesn't exist, returns null.
final int? counter = prefs.getInt('counter');
// Try reading data from the 'repeat' key. If it doesn't exist, returns null.
final bool? repeat = prefs.getBool('repeat');
// Try reading data from the 'decimal' key. If it doesn't exist, returns null.
final double? decimal = prefs.getDouble('decimal');
// Try reading data from the 'action' key. If it doesn't exist, returns null.
final String? action = prefs.getString('action');
// Try reading data from the 'items' key. If it doesn't exist, returns null.
final List<String>? items = prefs.getStringList('items');

// Remove data for the 'counter' key.

await prefs.remove('counter');