flutter findAncestorStateOfType错误

The method ‘findAncestorStateOfType’ was called on null. Receiver: null Tried calling: findAncestorStateOfType<NavigatorState>()

出现上述错误的情况是由一个对话框需要导航到另外一个页面出现的,最后修复了,是没有导入BuildContext所致。

Flutter List.map()时获取索引值index

list =

List songListByUser = [
  {“score”: “A-“, “歌名”: “童年”, ‘id’: 1},
  {“score”: “C+”, “歌名”: “之乎者也”, ‘id’: 2},
  {“score”: “B+”, “歌名”: “野百合春天”, ‘id’: 3},
  {“score”: “D+”, “歌名”: “恋曲1990”, ‘id’: 4},
  {“score”: “D+”, “歌名”: “恋曲”, ‘id’: 5},
  {“score”: “B-“, “歌名”: “歌”, ‘id’: 6},
];
    return list
        .asMap()
        .keys
        .map((value) => ListTile(
              leading: Icon(
                Icons.music_note,
                color: Colors.green,
              ),
              trailing: Icon(Icons.keyboard_arrow_right),
              title: Text(list[value][‘歌名’].toString()),
              onTap: () {
                var mapstr = json.encode(list[value]).toString();
              },
            ))
        .toList();

Flutter 动态更新CircleAvatar的图片

CircleAvatar有一个参数是 backgroundImage, 它是一个Imageprovider. 通过选择手机图片或者拍照后,获取到的是一个PickedFile , 我用的是

image_picker: ^0.6.7+17插件
PickedFile _imageFile;
    ImagePicker imagePicker = ImagePicker();
    var image = await imagePicker.getImage(source: imageSource);
    setState(() {
      _imageFile = image;
      _avatarImage = File(image.path);
    });
定义一个文件类型的变量_avatarImage, 然后通过Image.file(_avatarImage).image 赋值给backgroundImage就行了。AssetImage(“assets/images/cat.jpg”)是默认值。
File _avatarImage;
backgroundImage: _avatarImage == null
                      ? AssetImage(“assets/images/cat.jpg”)
                      : Image.file(_avatarImage).image,

Flutter 如何将方法当做一个变量传递

如下所示,其中action 就是函数,写成void Function() action, 其它地方调用的时候就 tapBlueText(“文本”, action), action这里不用括号 action().

Widget tapBlueText(String text, void Function() action) {
    return GestureDetector(
      onTap: action,
      child: Text(
        text
      ),
    );
  }

Flutter List 或Map数据转ListView

数据清单如下:
List songListByUser = [
  {“score”: “A-“, “歌名”: “童年”, ‘id’: 1},
  {“score”: “C+”, “歌名”: “之乎者也”, ‘id’: 2},
  {“score”: “B+”, “歌名”: “野百合春天”, ‘id’: 3},
  {“score”: “D+”, “歌名”: “恋曲1990”, ‘id’: 4},
  {“score”: “D+”, “歌名”: “恋曲”, ‘id’: 5},
  {“score”: “B-“, “歌名”: “歌”, ‘id’: 6},
];
返回为List<Widget>
List<Widget> _listViewByUser() {
  return songListByUser
      .map((f) => ListTile(
            leading: Icon(
              Icons.music_note,
              color: Colors.green,
            ),
            trailing: Icon(Icons.keyboard_arrow_right),
            title: Text(f[‘歌名’].toString() + ‘(‘ + f[‘score’].toString() + ‘)’),
            onTap: () => print(f[‘id’].toString()),
          ))
      .toList();
}
在需要使用的地方

 children: _listViewByUser(),

Win10 下ogg文件改名很卡的解决办法

用dos命令来改名或者删除即可。

1. CMD 命令打开Dos窗口,

2. cd 到该文件的目录,例如到c:\music

cd c:\music

3. 删除文件就是 del 文件名称,比如删除1.ogg的文件就是

del 1.ogg

4. 如果想把1.ogg改成2.ogg 就是这样

rename 1.ogg 2.ogg 就行了

Flutter 播放本地音乐并实现暂停,停止功能

用audioplayers插件播放本地音乐总是出错,查到可以使用AudioCache播放,但是又没有了停止和暂停功能,尝试了一下,用以下办法实现

AudioPlayer _audioPlayer;
AudioCache _audioCache;
    mode = PlayerMode.MEDIA_PLAYER;
    _audioPlayer = AudioPlayer(mode: mode);
    _audioCache = AudioCache(prefix: ‘audio/’);
//关键的一句在这里

_audioCache.fixedPlayer = _audioPlayer;
//播放的时候用_audioCache.play.
void _cacheplay() async {
    final result = await _audioCache.play(‘pfzl.mp3’, isNotification: true);
    if (result == 1) {
      print(‘succes’);
    }
  }
//暂停和停止是用_audioPlayer来实现
//暂停
  void _pause() async {
    final result = await _audioPlayer.pause();
    if (result == 1) {
      print(‘succes’);
    }
  }
  //停止播放
  _stop() async {
    final result = await _audioPlayer.stop();
    if (result == 1) {
      setState(() {
        _position = Duration();
      });
    }
  }

Flutter 如何读取原生的SharePreferences

Flutter 有个插件可以进行这个操作,插件地址,但是有两个地方需要注意:

  1. Android 代码写SharePreferences的时候是需要定义文件名称的。比如下面代码就是保存一个布尔值,而对于Flutter的这个插件,名称必须是FlutterSharedPreferences
    SharedPreferences sharedPreferences= mContext.getSharedPreferences("FlutterSharedPreferences",Context.MODE_PRIVATE);
    //步骤2: 实例化SharedPreferences.Editor对象
    SharedPreferences.Editor editor = sharedPreferences.edit();
    //步骤3:将获取过来的值放入文
    editor.putBoolean("flutter.connected",isON);
    //步骤4:提交
    editor.commit();

    2. 在Android 的代码里面,如果要写入键值,名称的前面必须加上”flutter.”,比如键值是connected,就需要写成flutter.connected.

在Android的原生代码里面进行如上操作后,flutter里面就可以正常的进行读取和保存了。第一,不需要文件名称,第二不需要再加flutter.

Flutter 与Android 的通讯 -BasicMessageChannel方式

Flutter 端

static const BasicMessageChannel<String> messageChannel = BasicMessageChannel<String>(“flutter-drumkaka”, StringCodec());
var receivedMessage = “”
//messageChannel.setMessageHandler(_handlePlatformIncrement);
Future<String> _handleNativeMessage(String message) async {
print(“message=$message”);
setState(() {

receivedMessage = message;
});
return “a return message”;
}
_handNativeMessage(“this is from Flutter”);

 

Android 端

String CHANNEL = "flutter-drumkaka";
BasicMessageChannel<String> messageChannel = new BasicMessageChannel<>(getFlutterEngine().getDartExecutor().getBinaryMessenger(), CHANNEL, StringCodec.INSTANCE);
messageChannel.
        setMessageHandler(new BasicMessageChannel.MessageHandler<String>() {

            @Override
            public void onMessage(@Nullable String message, @NonNull BasicMessageChannel.Reply<String> reply) {
                showMessage(message);                
            }
        });

messageChannel.send("this is from Android Native");

python cv2 获取矩形,居中,旋转

下面的代码可以让一个图片中的任意位置,角度的矩形,旋转到正确的位置,并且居中显示。
import cv2
import numpy as np
import matplotlib.pyplot as plt
from pynput import keyboard,mouse

def plt_show(image):
plt.imshow(image)
plt.axis('off')
plt.show()

def show(image):
cv2.imshow("raw", image)
cv2.waitKey(0)

def move_right():
print("moving right")

def move_left():
print("moving left")

def move_up():
print("moving up")

def move_down():
print("moving down")

def save_picture(angel,image):
cv2.imwrite("%s/%s.jpg" % ('image', angel),image.shape[0],image.shape[1])

def handlToGray(image):
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
ret, TRE = cv2.threshold(gray, 50, 255, cv2.THRESH_BINARY) # 图像二值化
return TRE
#图像转动一定角度
def rotate_bound(image, angle):
# grab the dimensions of the image and then determine the
# center
(h, w) = image.shape[:2]
(cX, cY) = (w // 2, h // 2)

# grab the rotation matrix (applying the negative of the
# angle to rotate clockwise), then grab the sine and cosine
# (i.e., the rotation components of the matrix)
M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0)
cos = np.abs(M[0, 0])
sin = np.abs(M[0, 1])

# compute the new bounding dimensions of the image
nW = int((h * sin) + (w * cos))
nH = int((h * cos) + (w * sin))

# adjust the rotation matrix to take into account translation
M[0, 2] += (nW / 2) - cX
M[1, 2] += (nH / 2) - cY

# perform the actual rotation and return the image
return cv2.warpAffine(image, M, (nW, nH))
#图像按照给定的x,y 值进行平移
def moving_bound(image,x,y):
(h, w) = image.shape[:2]
M = np.float32([[1,0,-x],[0,1,-y]])
return cv2.warpAffine(image, M, (w, h))
#找到矩形的旋转角度
def find_rect(image):
gray = handlToGray(image)
contours, hierarchy = cv2.findContours(gray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
rect = cv2.minAreaRect(contours[0])
return rect


#获取矩形的偏移坐标
def getoffset(image):
(h, w) = image.shape[:2]
cx = int(w / 2)
cy = int(h / 2)
x_left = 0;
x_right = 0;
y_up = 0;
y_down = 0;

x_total = 0;
y_total = 0;

# 获取左边边框
for i in range(cx, 0, -1):
mx = image[cy][i] # 先取高度,再取宽度
if (mx == 0):
x_left = i
break
# 获取右边边框
for i in range(cx, w, 1):
mx = image[cy][i]
if (mx == 0):
x_right = i
break
x_total = x_right - x_left

# 获取上边框
for i in range(cy, 0, -1):
my = image[i][cx]
if (my == 0):
y_up = i
break
# 获取下边框
for i in range(cy, h, 1):
mx = image[i][cx]
if (mx == 0):
y_down = i
break
y_total = y_down - y_up

x_offset = (x_left + x_total / 2) - cx
y_offset = (y_up + y_total / 2) - cy

return x_offset, y_offset, x_total, y_total



def on_press(key):
pass

def on_release(key):
if key == keyboard.Key.esc: # Stop listener
return False
elif key == keyboard.Key.right:
move_right()
elif key == keyboard.Key.left:
move_left()
elif key == keyboard.Key.up:
move_up()
elif key == keyboard.Key.down:
move_down()



def on_move(x, y):
pass

def on_click(x, y, button, pressed):
pass

def on_scroll(x, y, dx, dy):
pass

def main():

image = cv2.imread("image/raw2.jpg")
rect = find_rect(image)
angle = rect[2] #角度
im = rotate_bound(image, -angle)
rect = find_rect(im)
print(rect)
x,y = rect[0]
width, height = rect[1]
box = cv2.boxPoints(rect)
(h, w) = im.shape[:2]
cx = int(w / 2)
cy = int(h / 2)
im = moving_bound(im,x-cx,y-cy)
if width < height:
im = rotate_bound(im, 90)
TRE = handlToGray(im)
plt_show(TRE)

main()

# Collect events until released
keyboard_listener = keyboard.Listener(on_press=on_press, on_release=on_release)
mouse_listener = mouse.Listener(on_click=on_click, on_move=on_move, on_scroll=on_scroll)
lst = [keyboard_listener, mouse_listener]

for t in lst: t.start()
for t in lst: t.join()