Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

dart - Create a Stream who listens to File-Changes in Flutter

I am trying to keep the number of "Coins" up-to-date with the help of a Stream who listens for File-Changes. I tried to create this Stream:

import 'dart:async';
import 'dart:io';
import 'package:path_provider/path_provider.dart';

enum CoinStatus { Same, Changed }

class CoinStream {
  String uid;
  StreamController<CoinStatus> coinStreamController =
      StreamController<CoinStatus>();

  CoinStream({this.uid}) {
    startReadingFile(uid).listen((event) {
    coinStreamController.add(_getCoinStatus(event));
    });
  }

  CoinStatus _getCoinStatus(FileSystemEvent fse) {
    return fse.type == FileSystemEvent.modify
      ? CoinStatus.Changed
      : CoinStatus.Same;
  }

  //method to start listening to the file
  Stream startReadingFile(String uid) async* {
    final directory = await getApplicationDocumentsDirectory();
    final file = File('$directory.path/users/$uid');
    yield file.watch();
  }

  close() {
    coinStreamController.close();
    }
 }

I am using a StreamProvider with initialData. But it does not seem to work, as the value of:

Provider.of<CoinStatus>(context).toString() 

is always the value of the initialData.

class Wrapper extends StatelessWidget {
@override
Widget build(BuildContext context) {
final user = Provider.of<PixanaUser>(context);

if (user == null) {
  return SignInPage();
} else {
  return StreamProvider<CoinStatus>.value(
      initialData: CoinStatus.Same,
      value: CoinStream(
              uid: Provider.of<PixanaUser>(context, listen: false).uid)
          .coinStreamController
          .stream,
      child: Home());
  }
 }
}

I hope you guys can help me..

question from:https://stackoverflow.com/questions/65877905/create-a-stream-who-listens-to-file-changes-in-flutter

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...