当前位置:网站首页>A Fletter version of Notepad
A Fletter version of Notepad
2022-07-01 13:13:00 【xiangxiongfly915】
a Flutter Version of Notepad

Defining entity classes
class NoteInfo {
final String name;
final String path;
final DateTime updateTime;
const NoteInfo(this.name, this.path, this.updateTime);
}
Home code
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'EditNodePage.dart';
import 'FileUtils.dart';
import 'NoteInfo.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter diary ',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: ' diary '),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<NoteInfo> noteList = [];
@override
void initState() {
loadNotes();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: noteList.isEmpty ? _buildEmpty() : _buildList(),
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.add, color: Colors.white),
backgroundColor: Colors.blue,
onPressed: () async {
var result = await Navigator.of(context).push(MaterialPageRoute(builder: (context) {
return const EditNodePage();
}));
loadNotes();
},
),
);
}
/// Empty page
_buildEmpty() {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.hourglass_empty_sharp,
color: Colors.black.withOpacity(0.6),
size: 40,
),
Text(
" empty , Come and write a diary ",
style: TextStyle(color: Colors.black.withOpacity(0.6)),
),
],
),
);
}
_buildList() {
return ListView.separated(
itemBuilder: (BuildContext context, int index) {
return InkWell(
onTap: () async {
var result = await Navigator.of(context).push(MaterialPageRoute(builder: (context) {
return EditNodePage(path: noteList[index].path);
}));
loadNotes();
},
child: ListTile(
title: Text(noteList[index].name),
subtitle: Text("${noteList[index].updateTime}"),
),
);
},
separatorBuilder: (BuildContext context, int index) => const Divider(height: 1),
itemCount: noteList.length,
);
}
/// Load Journal
loadNotes() async {
var parentDir = await getTemporaryDirectory();
List<FileSystemEntity> dirList = parentDir.listSync(recursive: false);
List<FileSystemEntity> fileList = [];
for (var dir in dirList) {
if ((await dir.stat()).type == FileSystemEntityType.file) {
fileList.add(dir);
}
}
fileList.sort((f1, f2) {
try {
DateTime dateTime1 = File(f1.path).lastModifiedSync();
DateTime dateTime2 = File(f2.path).lastModifiedSync();
return dateTime2.microsecondsSinceEpoch - dateTime1.microsecondsSinceEpoch;
} catch (e) {
return 0;
}
});
noteList.clear();
for (var f in fileList) {
File file = File(f.path);
if (file.path.endsWith("txt")) {
noteList.add(NoteInfo(FileUtils.getFileName(file.path), file.path, file.lastModifiedSync()));
}
}
setState(() {});
}
}
Edit page code
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'FileUtils.dart';
class EditNodePage extends StatefulWidget {
final String? path;
const EditNodePage({Key? key, this.path}) : super(key: key);
@override
State<StatefulWidget> createState() {
return _EditNodePageState();
}
}
class _EditNodePageState extends State<EditNodePage> {
late TextEditingController _titleController;
late TextEditingController _contentController;
@override
void initState() {
_titleController = TextEditingController();
_contentController = TextEditingController();
loadData();
super.initState();
}
@override
void dispose() {
_titleController.dispose();
_contentController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(" edit "),
actions: [
IconButton(onPressed: save, icon: const Icon(Icons.done)),
],
),
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
TextField(
controller: _titleController,
decoration: const InputDecoration(hintText: " Please enter the journal name "),
),
Expanded(
child: TextField(
textAlignVertical: TextAlignVertical.top,
controller: _contentController,
decoration: const InputDecoration(hintText: " Start your story "),
maxLength: 2000,
maxLines: null,
minLines: 1,
keyboardType: TextInputType.multiline,
),
),
],
),
),
),
);
}
loadData() async {
if (widget.path != null) {
String fileName = FileUtils.getFileName(widget.path);
String content = const Utf8Decoder().convert(await File(widget.path!).readAsBytes());
setState(() {
_titleController.text = fileName;
_contentController.text = content;
});
}
}
save() async {
try {
String title = _titleController.text;
String content = _contentController.text;
var parentDir = await getTemporaryDirectory();
var file = File("${parentDir.path}/$title.txt");
bool exists = file.existsSync();
if (!exists) {
file.createSync();
}
file.writeAsStringSync(content);
Navigator.of(context).pop(title);
} on Exception catch (e) {
print(e);
}
}
}
The code download
边栏推荐
- Example code of second kill based on MySQL optimistic lock
- JS变色的乐高积木
- Fundamentals of number theory and its code implementation
- Colorful five pointed star SVG dynamic web page background JS special effect
- 【牛客刷题-SQL大厂面试真题】NO2.用户增长场景(某度信息流)
- 【开发大杀器】之Idea
- Run PowerShell script prompt "because running script is prohibited on this system" solution
- Scene function of wooden frame
- I spent tens of thousands of dollars to learn and bring goods: I earned 3 yuan in three days, and the transaction depends on the bill
- 基于开源流批一体数据同步引擎 ChunJun 数据还原 —DDL 解析模块的实战分享
猜你喜欢

Jenkins+webhooks- multi branch parametric construction-

VM virtual machine configuration dynamic IP and static IP access

Redis explores cache consistency

游戏公会在去中心化游戏中的未来

Colorful five pointed star SVG dynamic web page background JS special effect
![[development of large e-commerce projects] performance pressure test - basic concept of pressure test & jmeter-38](/img/50/819b9c2f69534afc6dc391c9de5f05.png)
[development of large e-commerce projects] performance pressure test - basic concept of pressure test & jmeter-38

Ikvm of toolbox Net project new progress

Based on the open source stream batch integrated data synchronization engine Chunjun data restore DDL parsing module actual combat sharing

Manage nodejs with NVM (downgrade the high version to the low version)

Shell script imports stored procedures into the database
随机推荐
Machine learning - performance metrics
SSO and JWT good article sorting
Flutter SQLite使用
Topic 2612: the real topic of the 12th provincial competition of the Blue Bridge Cup in 2021 - the least weight (enumerating and finding rules + recursion)
简单的两个圆球loading加载
Shangtang technology crash: a script written at the time of IPO
Huawei HMS core joins hands with hypergraph to inject new momentum into 3D GIS
Research Report on China's software outsourcing industry investment strategy and the 14th five year plan Ⓡ 2022 ~ 2028
There are still many things to be done in the second half of the year
软件测试中功能测试流程
[development of large e-commerce projects] performance pressure test - basic concept of pressure test & jmeter-38
Use Net core access wechat official account development
Report on the "14th five year plan" and investment strategy recommendations for China's industrial robot industry 2022 ~ 2028
R language uses conf of yardstick package_ The mat function calculates the confusion matrix of the multiclass model on each fold of each cross validation (or resampling), and uses the summary to outpu
Simple Fibonacci (recursive)
Report on the "14th five year plan" and scale prospect prediction of China's laser processing equipment manufacturing industry Ⓢ 2022 ~ 2028
基于mysql乐观锁实现秒杀的示例代码
Flinkcdc should extract Oracle in real time. What should be configured for oracle?
运行Powershell脚本提示“因为在此系统上禁止运行脚本”解决办法
leetcode 322. Coin change (medium)