Flutter Image Widget不会在更改状态时更新

zbwhf8kr  于 2022-11-30  发布在  Flutter
关注(0)|答案(3)|浏览(189)

我正在创建一个使用滑块的图像编辑器应用程序,类似于Instagram,我正在使用库image/image.dart。问题是,一旦你移动滑块,它就会更新图像,但就在那时,如果你再次移动它,它就不会更新。
我已经按预期设置了所有内容,setState()函数如flutter所要求的那样,但我不知道为什么它不会再次更新。

import 'dart:io';
import 'dart:ui';
import 'package:flutter/material.dart';

import 'package:image/image.dart' as br;
import 'package:path_provider/path_provider.dart';
import 'package:image_picker/image_picker.dart';

class ImageManager extends StatefulWidget {

  @override
  State<StatefulWidget> createState() {
    return _ImageManagerState();
  }
}

class _ImageManagerState extends State<ImageManager> {
  File imageFile;
  br.Image image;
  Image _imageWidget;

  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();

    return directory.path;
  }

  // get tmp file
  Future<File> get _localFile async {
    final path = await _localPath;
    return File('$path/tmp.jpg');
  }

  // pick image on button click
  Future<void> _pickImage(ImageSource source) async{
    File selectedFile = await ImagePicker.pickImage(source: source);
    br.Image selectedImage;
    if (selectedFile != null){
      selectedImage = br.decodeImage(selectedFile.readAsBytesSync());
      br.grayscale(selectedImage);

      selectedFile.writeAsBytesSync(br.encodeJpg(selectedImage));
    }

    setState((){
      image = selectedImage;
      imageFile = selectedFile;
      _imageWidget = Image.file(imageFile);
    });
  }

  // MAIN PROBLEM, UPDATING THE CONTRAST WILL ONLY DO IT ONCE
  Future<void> updateContrast(value) async{
    File contrastFile = imageFile;
    br.Image contrast = br.decodeImage(contrastFile.readAsBytesSync());
    contrast = br.adjustColor(contrast, contrast: value);
    contrastFile.writeAsBytesSync(br.encodeJpg(contrast));

    // Save the thumbnail as a jpg.
    File path = await _localFile;
    path.writeAsBytesSync(br.encodeJpg(contrast));
    setState(() {
      image = contrast;
      imageFile = contrastFile;
      if(path != null){
        _imageWidget = Image.file(path);
        print(value);
      }

    });
  }

  // 
  Widget _buildImage(BuildContext context){
    return Column(
      children: [
        Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.width,
          child: _imageWidget,
        ),
        Column(
          children: [
            Container(
              padding: const EdgeInsets.only(left: 8, right: 8),
              child: Column(
                children: <Widget>[
                  // contrast
                  Text("Contraste"),
                  Padding(
                    padding: const EdgeInsets.only(bottom: 4.0, top: 0.0),
                    child: Container(
                      child: Slider(
                        min: 0.0,
                        max: 1.0,
                        divisions: 100,
                        value: _contrast,
                        activeColor: Colors.blue[500],
                        inactiveColor: Colors.blue[50],
                        label: "${(_contrast *100).round()}",
                        onChanged: (value) async{
                          changeContrast(value);
                        },
                        onChangeEnd: (value) async{
                          updateContrast(value);
                        },
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ]
    );
  }

我希望每次更改滑块时图像都会更新。

i5desfxk

i5desfxk1#

imageCache.clear()将完成此工作。
我也不能重新加载图像保存在本地屏幕上。从调试,我观察到旧的图像实际上被删除,新的图像被复制到那里,但屏幕上没有任何变化。下面是你需要的代码。
因此,在Scaffold的主体中,我创建了一个FutureBuilder,它调用另一个函数reload(),然后该函数加载文件并返回图像。

FutureBuilder(
future: reload(),
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
    if(snapshot.connectionState == ConnectionState.done){
        return snapshot.data;
    }  
    else{
        return CircularProgressIndicator();
    }
},
),

下面是reload()函数:

reload() async {
String path = "path of your image";
File profileImage = File("$path/name.jpg");

if(profileImage.existsSync() == false){
  return Text("File Not Found");
}
else{
  imageCache.clear();
  return Image.file(profileImage);
}
}

我查了Flutter的github,jamesncl已经建议过了。

cigdeys3

cigdeys32#

我解决了这个问题,这对我来说很奇怪,但如果有人能解释一下,我会很感激。

Future<void> adjustImage() async{
  File toAdjustFile = imageFile;
  br.Image toAdjust = br.decodeImage(toAdjustFile.readAsBytesSync());
  toAdjust = br.adjustColor(toAdjust, contrast: _contrast, brightness: _brightness, exposure: _exposure);
  setState(() {
    _imageWidget = Image.memory(br.encodeJpg(toAdjust));
  });
}

我重构了我的函数,并将小部件设置为另一个构造函数Image.memory()

rhfm7lfc

rhfm7lfc3#

使用Image.memory代替Image.file,我代码中一行

Image.memory(
          File(widget.imagePath).readAsBytesSync(),),

相关问题